package com.example.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.example.dao.export.DeptMapper;
import com.example.dao.export.EmpMapper;
import com.example.dao.export.SalGradeMapper;
import com.example.entity.export.DeptVo;
import com.example.entity.export.EmpVo;
import com.example.entity.export.SalGradeVo;
import com.example.listener.Import.EmpListener;
import com.example.service.ExcelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: TODO
 * @Author runto
 * @Date 2023/11/4 8:22
 * @PackageName:com.example.service.impl
 * @ClassName: ExcelServiceImpl
 * @Version 1.0
 */

@Service
public class ExcelServiceImpl implements ExcelService {

    private static final Logger logger = LoggerFactory.getLogger(ExcelServiceImpl.class);


    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private SalGradeMapper salGradeMapper;

    public void exportInfo(HttpServletResponse response)throws IOException {
        OutputStream outputStream=response.getOutputStream();
        ExcelWriter writer = EasyExcel.write(outputStream).excelType(ExcelTypeEnum.XLSX).build();
        try {
            List<EmpVo> empList = getExportEmpData();
            List<DeptVo> deptList = getExportDeptData();
            List<SalGradeVo> salGradeList = getExportSalGradeData();
            logger.info("开始导出员工薪资信息...{}",deptList);
            this.setExcelResponseProp(response, "员工薪资信息");
            // 模拟根据条件在数据库分页查询数据
            for(int j=1;j<=3;j++){
                if(j==1){

                    List<EmpVo> userList = new ArrayList<>();
                    for (EmpVo item:empList){
                        EmpVo empDto =new EmpVo();
                        empDto.setEmpNo(item.getEmpNo());
                        empDto.setDeptNo(item.getDeptNo());
                        empDto.setEName(item.getEName());
                        //不支持写入时间类型
                        empDto.setHireDate(item.getHireDate());
                        empDto.setJob(item.getJob());
                        empDto.setSal(item.getSal());
                        empDto.setComm(item.getComm());
                        empDto.setMgr(item.getMgr());
                        userList.add(empDto);
                    }
                    //创建新的sheet页
                    WriteSheet writeSheet = EasyExcel.writerSheet("用户信息").head(EmpVo.class).build();
                    //将list集合中的对象写到对应的sheet中去
                    writer.write(userList,writeSheet);
                }
                else if(j==2){
                    List<DeptVo> BList = new ArrayList<>();
                    for (DeptVo item:deptList){
                        DeptVo deptVo =new DeptVo();
                        deptVo.setDName(item.getDName());
                        deptVo.setDeptNo(item.getDeptNo());
                        deptVo.setLoc(item.getLoc());
                        BList.add(deptVo);
                    }
                    //创建新的sheet页
                    WriteSheet writeSheet = EasyExcel.writerSheet("部门信息").head(DeptVo.class).build();
                    //将list集合中的对象写到对应的sheet中去
                    writer.write(BList,writeSheet);
                }else{
                    List<SalGradeVo> userList = new ArrayList<>();
                    for (SalGradeVo item:salGradeList){
                        SalGradeVo salGradeVo =new SalGradeVo();
                        salGradeVo.setGrade(item.getGrade());
                        salGradeVo.setLoSal(item.getLoSal());
                        salGradeVo.setHiSal(item.getHiSal());
                        userList.add(salGradeVo);
                    }
                    //创建新的sheet页
                    WriteSheet writeSheet = EasyExcel.writerSheet("薪资等级信息").head(SalGradeVo.class).build();
                    //将list集合中的对象写到对应的sheet中去
                    writer.write(userList,writeSheet);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            writer.finish();
            outputStream.flush();
            outputStream.close();
        }
    }

    @Override
    public void importInfo(MultipartFile file) {
        try {
            //获取文件的输入流
            InputStream inputStream = file.getInputStream();
            List<EmpVo> list = EasyExcel.read(inputStream) //调用read方法
                    .registerReadListener(new EmpListener())//注册自定义监听器，字段校验可以在监听器内实现
                    .head(EmpVo.class) //对应导入的实体类
                    .sheet(0) //导入数据的sheet页编号，0代表第一个sheet页，如果不填，则会导入所有sheet页的数据
                    .headRowNumber(1) //列表头行数，1代表列表头有1行，第二行开始为数据行
                    .doReadSync(); //开始读Excel，返回一个List<T>集合，继续后续入库操作

            //模拟导入数据库操作
            for (EmpVo empVo:list){
                logger.info("开始入库...");
            }
        }catch (IOException exception){
            throw new  RuntimeException(exception);
        }

    }

    //查询员工信息
    private List<EmpVo> getExportEmpData(){
        List<EmpVo> empVos = empMapper.selectAllEmp();
        return empVos;
    }

    //查询员工信息
    private List<DeptVo> getExportDeptData(){
        List<DeptVo> DeptVos = deptMapper.selectAllDept();
        return DeptVos;
    }
    //查询员工信息
    private List<SalGradeVo> getExportSalGradeData(){
        List<SalGradeVo> SalGradeVos = salGradeMapper.selectAllSalGrade();
        return SalGradeVos;
    }

    /**
     * 设置响应结果
     *
     * @param response    响应结果对象
     * @param rawFileName 文件名
     * @throws UnsupportedEncodingException 不支持编码异常
     */
    private void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        //设置内容类型
        response.setContentType("application/vnd.vnd.ms-excel");
        //设置编码格式
        response.setCharacterEncoding("utf-8");
        //设置导出文件名称（避免乱码）
        String fileName = URLEncoder.encode(rawFileName.concat(".xlsx"), "UTF-8");
        // 设置响应头
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
    }
}
